import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
import { DefaultStage } from '../default-stage';
import { RawAssetsUrl } from '../../raw-assets-info';
import { PBRMaterial } from '@babylonjs/core/Materials/PBR/pbrMaterial';
import * as Data from '../../data/data';


class DefaultModel {

    private static model: TransformNode;

    public static display(show: boolean): void {
        this.model.getChildMeshes().forEach(m => m.isVisible = show);
    }

    public static reset(): void {
        this.model.position.set(0, 0, 0);
        this.model.rotation.set(0, 0, 0);
        this.model.scaling.set(1, 1, 1);
        this.display(true);
    }

    public static initialize(stage: DefaultStage): void {
        this.model = new TransformNode('default-model', stage.mainScene);

        const loader = stage.loader(stage.mainScene);
        const ns = loader.getMeshTaskInfo(RawAssetsUrl.changjing)?.loadedMeshes;

        const tex = loader.getCubeTextureTaskInfo(RawAssetsUrl.lightCubePX)?.texture!;

        ns?.forEach(m => {
            if (m.material) {
                (m.material as PBRMaterial).reflectionTexture = tex;
            }
            m.parent = DefaultModel.model;
        });

        this.bindData();
    }

    private static bindData(): void {
        const model = this.model;
        Data.positionX.onChange((o, n) => {
            model.position.x = n;
        });
        Data.positionY.onChange((o, n) => {
            model.position.y = n;
        });
        Data.positionZ.onChange((o, n) => {
            model.position.z = n;
        });
        Data.rotationX.onChange((o, n) => {
            model.rotation.x = n;
        });
        Data.rotationY.onChange((o, n) => {
            model.rotation.y = n;
        });
        Data.rotationZ.onChange((o, n) => {
            model.rotation.z = n;
        });
        Data.scale.onChange((o, n) => {
            model.scaling.set(n, n, n);
        });
    }
}


export { DefaultModel };